const express = require('express')
const User = require('./models/users')
const md5 = require('blueimp-md5')
const Rpromise = require('./promise')

const router = express.Router()

router.get('/', (req, res) => {
  res.render('index.html')
})
router.get('/login', (req, res) => {
  console.log(req.query.code)
  res.render('login.html', {
    code: req.query.code,
  })
})
router.post('/login', (req, res) => {})

router.get('/register', (req, res) => {
  res.render('register.html')
})
router.post('/register', (req, res) => {
  let body = req.body
  User.findOne({ $or: [{ email: body.email }, { nickname: body.nickname }] })
    .then((data) => {
      if (data) {
        return res.status(200).json({
          err_code: 1,
          message: 'email or nickname alread existent.',
        })
      }
      //重复加密
      body.password = md5(md5(body.password))
      new User(body)
        .save()
        .then((user) => {
          return res.status(200).json({ err_code: 0, message: 'ok' })
        })
        .catch((err) => {
          return res.status(500).json({
            err_code: 500,
            message: err,
          })
        })
    })
    .catch((err) => {
      if (err) {
        return res.status(500).json({
          err_code: 500,
          // message: 'Server Error',
          message: err,
        })
      }
    })
})

module.exports = router
